import { getAddress } from '@/api'
import router from '@/router'
import { defineStore } from 'pinia'

export const useAddressStore = defineStore('address', () => {
  //地址数据数组
  const cities = ref<IAddress[]>()

  //默认地址
  const defaultId = computed(() => {
    const item = localStorage.getItem('address')
    if (item) {
      return JSON.parse(item)
    }
    return cities.value?.filter((item) => item.id === '1')
  })

  // 默认地址
  const elected = ref()

  //选中地址
  const selectedId = (id?: string) => {
    if (!id) {
      return (elected.value = defaultId)
    }
    return (elected.value = cities.value?.filter((item) => item.id === id))
  }

  const getCities = async (token: string) => {
    //判断token
    if (!token && token.length !== 32) {
      return router.push({ name: 'login' })
    }

    //请求接口
    const citiesString = await getAddress({ token })

    cities.value = citiesString
  }
  return {
    getCities,
    cities,
    defaultId,
    selectedId
  }
})
